"""Main module."""
import sys
import toml
import os
import subprocess
import shlex

# ------------------ 读取白名单 --------------------
def whitelist_read(file) :
    # print("---> 读取白名单")
    a = toml.load(file)
    # print("变量a的类型: %s" % type(a))
    # print("变量a的内容: %s" % a)
    # print("     |--> 白名单:\n \t%s" % a["database"]["list"][0])
    return  a["database"]["list"]


# ------------------ 检测白名单 --------------------
def pong_whitelist(domain_name) :
    # -c 1 只发送一个数据包
    # -w 1 超时时间1秒
    cmd = "ping -c 1 -w 1 %s" % domain_name
    args = shlex.split(cmd)

    try:
        subprocess.check_call(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        return True
    except subprocess.CalledProcessError:
        return False


if __name__ == "__main__":
    file = 'whitelist.toml'
    list = whitelist_read(file)
    print("------------------------- 白名单检测 ----------------------")
    i = 0
    for site in list:
        i += 1
        b = pong_whitelist(site["site"])
        s = "{1:^5}|{2:{0}<10}|{3:<30}|{4:<5}".format(chr(12288),i, site["title"],site["site"], "ok" if b else "bad")
        print(s)
    print("------------------------- OVER ----------------------")
